﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Windows.Forms;
using System.IO;
using PaliTextReader2.Utilities;
using mshtml;
using PaliTextReader2.Properties;
using ICSharpCode.SharpZipLib.Zip;
using System.Text.RegularExpressions;

namespace PaliTextReader2
{
    public partial class BookViewerControl : UserControl
    {
        int m_nNodeID = -1;
        int m_nFileID;
        int m_nScrollPos=-1;
        string m_strPTSPage = "";
        SelectBook m_dlgSelectBook;
       
        public delegate void LookUpHandler(string message);
        public event LookUpHandler LookUp;

        public BookViewerControl()
        {
            InitializeComponent();
        }

        public BookViewerControl(int nNodeID)
        {
            InitializeComponent();

            ContentsDS.FilesDataTable objFiles=m_objFilesTA.GetByNode(nNodeID);
            if (objFiles.Count > 0)
            {
                OpenBook(objFiles[0]);
                m_nNodeID = nNodeID;
                m_nFileID = objFiles[0].FileID;
                m_dlgSelectBook = new SelectBook(objFiles[0].FileID);
            }
        }

        public BookViewerControl(int FileID, string PTSPage)
        {
            InitializeComponent();

            m_strPTSPage = PTSPage;
            m_nFileID = FileID;

            ContentsDS.FilesDataTable objFiles = m_objFilesTA.GetByFileID(FileID);
            if (objFiles.Count > 0)
            {
                OpenBook(objFiles[0]);
                m_dlgSelectBook = new SelectBook(objFiles[0].FileID);
            }
        }

        public BookViewerControl(int FileID, int ScrollPos)
        {
            InitializeComponent();

            m_nScrollPos = ScrollPos;
            m_nFileID = FileID;
            ContentsDS.FilesDataTable objFiles = m_objFilesTA.GetByFileID(FileID);
            if (objFiles.Count > 0)
            {
                OpenBook(objFiles[0]);
                m_dlgSelectBook = new SelectBook(objFiles[0].FileID);
            }
        }

        private void OpenBook(ContentsDS.FilesRow objFile)
        {
            string strContent = Utility.GetBookContent(Utility.CanonDirectory, objFile.FileName);

            if (strContent.Length > 0)
            {
                if (!objFile.ShowBold)
                    strContent = Regex.Replace(strContent, "<(/)?b[^>]*>", string.Empty);

                if (!objFile.ShowFont)
                    strContent = Regex.Replace(strContent, "<(/)?span[^>]*>", string.Empty);

                strContent = strContent.Replace("<BODY>", "<BODY>\r\n" + Resources.InjectScript);
                ctlBrowser.DocumentText = strContent;
            }
        }

        private void ctlBrowser_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
        {
            mshtml.HTMLDocument CurrentDocument = (mshtml.HTMLDocument)ctlBrowser.Document.DomDocument;
            mshtml.IHTMLStyleSheet styleSheet = CurrentDocument.createStyleSheet("", 0);
            StreamReader streamReader = new StreamReader(Application.StartupPath + @"\style.css");
            string text = streamReader.ReadToEnd();
            streamReader.Close();
            styleSheet.cssText = text;

            if (m_nNodeID > 0)
            {
                ContentsDS.NodesDataTable objNodes = m_objNodesTA.GetNode(m_nNodeID);
                if (objNodes.Count > 0 && !objNodes[0].IsBookmarkNameNull())
                    ctlBrowser.Document.All["p" + objNodes[0].BookmarkName].ScrollIntoView(true);
            }

            if (m_strPTSPage != String.Empty)
            {
                ctlBrowser.Document.All["g" + m_strPTSPage].ScrollIntoView(true);
            }

            if (m_nScrollPos > -1)
                ctlBrowser.Document.Window.ScrollTo(0, m_nScrollPos);
        }

        private void ctlMILookup_Click(object sender, EventArgs e)
        {
            mshtml.HTMLDocument a = (mshtml.HTMLDocument)this.ctlBrowser.Document.DomDocument;
            String text = "";
            bool success = a.execCommand("Copy", false, text);
            if (success)
                OnLookUp((string)Clipboard.GetDataObject().GetData(DataFormats.StringFormat));
        }

        protected void OnLookUp(string message)
        {
            if (LookUp != null)
                LookUp(message);
        }

        public void ShowQuickNav()
        {
            if (m_dlgSelectBook.ShowDialog() == DialogResult.OK)
            {
                //if (m_nFileID != m_dlgSelectBook.FileID)
                //{//this is for quick switching to atthakatha/tika, but it doesn't work
                //    //MainWnd objMainWnd = (Application.OpenForms[0] as MainWnd);
                //    //BookViewerControl objViewForm = new BookViewerControl(m_dlgSelectBook.NodeID);
                //    //objMainWnd.OpenBookTab(objViewForm, m_dlgSelectBook.FileID);
                //}
                //else
                //{
                //}

                if (m_dlgSelectBook.NodeID > 0)
                {
                    ContentsDS.NodesDataTable objNodes = m_objNodesTA.GetNode(m_dlgSelectBook.NodeID);
                    if (objNodes.Count > 0 && !objNodes[0].IsBookmarkNameNull())
                        ctlBrowser.Document.All["p" + objNodes[0].BookmarkName].ScrollIntoView(true);
                }

                if (!String.IsNullOrEmpty(m_dlgSelectBook.PTSPage))
                    ctlBrowser.Document.All["g" + m_dlgSelectBook.PTSPage].ScrollIntoView(true);
                else if(m_dlgSelectBook.FileID>0)
                    ctlBrowser.Document.Window.ScrollTo(0, m_dlgSelectBook.ScrollPos);
            }
        }

        public void SaveState(AppState objState)
        {
            objState.OpenBooks.Add(new OpenBookInfo(m_nFileID, ScrollPos));
        }

        public void ShowFindDlg()
        {
            IOleCommandTarget cmdt;
            Object o = new object();
            Object i = new object();
            try
            {
                cmdt = (IOleCommandTarget)this.ctlBrowser.Document.DomDocument;
                cmdt.Exec(ref ComUtils.CommandGuid, (uint)MiscCommandTarget.Find,
                    0, ref i, ref i);
            }
            catch (Exception e)
            {
                System.Windows.Forms.MessageBox.Show(e.Message);
            }
        }

        private void ctlCopyMenuItem_Click(object sender, EventArgs e)
        {
            mshtml.HTMLDocument a = (mshtml.HTMLDocument)this.ctlBrowser.Document.DomDocument;
            String text = "";
            bool success = a.execCommand("Copy", false, text);
        }

        public int FileID
        {
            get { return m_nFileID; }
        }

        public int ScrollPos
        {
            get
            {
                mshtml.HTMLDocument a = (mshtml.HTMLDocument)this.ctlBrowser.Document.DomDocument;
                string strValue = ctlBrowser.Document.Forms[0].All["ScrollTop"].GetAttribute("value");
                return Int32.Parse(strValue == "" ? "0" : strValue);
            }
        }
    }
}
